package com.greenant.store.view;

import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.List;

import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.os.Handler;
import android.os.Looper;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.avos.avoscloud.AVException;
import com.avos.avoscloud.AVUser;
import com.avos.avoscloud.SaveCallback;
import com.greenant.store.AntHomeApplication;
import com.greenant.store.R;
import com.greenant.store.bean.AntGoods;
import com.greenant.store.bean.AntGoodsBase;
import com.greenant.store.bean.AntGoodsStyles;
import com.greenant.store.bean.GoodsKind;
import com.greenant.store.bean.GoodsList;
import com.greenant.store.bean.StoreInfo;
import com.greenant.store.service.RetrieveDataAsyn;
import com.greenant.store.service.RetrieveDataListener;
import com.greenant.store.utils.UtilTools;
import com.nostra13.universalimageloader.core.ImageLoader;

public class AddGoodsOnLineDialog extends Dialog implements android.view.View.OnClickListener {
	private Context mContext;
	private AntGoodsBase mAntGoods;
	private StoreInfo mStoreInfo;
	
	private ImageView mIvImage;
	private Button mBtnCancel;
	private Button mBtnAdd;
	private TextView mTvPromptShelf;
	private TextView mTvGoodsTitle;
	private TextView mTvGoodsDes;
	private EditText mEtPricePurchase;
	private EditText mEtPriceSell;
	private EditText mEtDiscount;
	private EditText mEtPriceByDiscount;
	private EditText mEtStore;
	
	private DecimalFormat mDecimalFormat;
	private boolean isCommiting = false;
	
	private double mOriginPricePurchase = 0;
	private double mOriginPriceSell = 0;
	private double mOriginDiscount = 0;
	private double mOriginStore = 0;
	
	private double mTempPricePurchase = 0;
	private double mTempPriceSell = 0;
	private double mTempDiscount = 0;
	private double mTempStore = 0;
	
	public interface AddResultListener {
		public void addSuccessful(AntGoods antGoods);
	}
	private AddResultListener mAddResultListener;
	
	private Handler mHandler = new Handler(Looper.getMainLooper());
	
	private TextWatcher mTextWatcherForPricePurchase = new TextWatcher() {
		@Override
		public void onTextChanged(CharSequence s, int start, int before, int count) {
			try{
				double pricePurchase = Double.valueOf(s.toString());
				if(pricePurchase < 0) {
					mEtPricePurchase.setText(String.valueOf(Math.abs(pricePurchase)));
				}
				else {
					mTempPricePurchase = pricePurchase;
				}
			}
			catch(Exception e) {
				mTempPricePurchase = 0;
				e.printStackTrace();
			}
		}
		
		@Override
		public void beforeTextChanged(CharSequence s, int start, int count,
				int after) {
		}
		
		@Override
		public void afterTextChanged(Editable s) {
		}
	};
	
	private TextWatcher mTextWatcherForPriceSell = new TextWatcher() {
		@Override
		public void onTextChanged(CharSequence s, int start, int before, int count) {
			try{
				double priceSell = Double.valueOf(s.toString());
				if(priceSell < 0) {
					mEtPriceSell.setText(String.valueOf(Math.abs(priceSell)));
				}
				else {
					mTempPriceSell = priceSell;
					
					if(mTempDiscount > 0) {
						mEtPriceByDiscount.setText(mDecimalFormat.format(mTempPriceSell * mTempDiscount / 10));
					}
					else if(mTempDiscount == 0){
						mEtPriceByDiscount.setText(mDecimalFormat.format(mTempPriceSell));
					}
				}
			}
			catch(Exception e) {
				mTempPriceSell = 0;
				e.printStackTrace();
			}
		}
		
		@Override
		public void beforeTextChanged(CharSequence s, int start, int count,
				int after) {
		}
		
		@Override
		public void afterTextChanged(Editable s) {
		}
	};
	
	private TextWatcher mTextWatcherForDiscount = new TextWatcher() {
		@Override
		public void onTextChanged(CharSequence s, int start, int before, int count) {
			try{
				double discount = Double.valueOf(s.toString());
				if(discount < 0) {
					mEtDiscount.setText(String.valueOf(Math.abs(discount)));
				}
				else if(discount > 10) {
					mEtDiscount.setText(String.valueOf(10));
				}
				else {
					mTempDiscount = discount;
					
					if(mTempDiscount > 0) {
						mEtPriceByDiscount.setText(mDecimalFormat.format(mTempPriceSell * mTempDiscount / 10));
					}
					else if(mTempDiscount == 0){
						mEtPriceByDiscount.setText(mDecimalFormat.format(mTempPriceSell));
					}
				}
			}
			catch(Exception e) {
				mTempDiscount = 0;
				e.printStackTrace();
			}
		}
		
		@Override
		public void beforeTextChanged(CharSequence s, int start, int count,
				int after) {
		}
		
		@Override
		public void afterTextChanged(Editable s) {
		}
	};
	
	private TextWatcher mTextWatcherForStore = new TextWatcher() {
		@Override
		public void onTextChanged(CharSequence s, int start, int before, int count) {
			try{
				double store = Double.valueOf(s.toString());
				if(store < 0) {
					mEtStore.setText(String.valueOf(Math.abs(store)));
				}
				else {
					mTempStore = store;
				}
			}
			catch(Exception e) {
				mTempStore = 0;
				e.printStackTrace();
			}
		}
		
		@Override
		public void beforeTextChanged(CharSequence s, int start, int count,
				int after) {
		}
		
		@Override
		public void afterTextChanged(Editable s) {
		}
	};
	
	public AddGoodsOnLineDialog(Context context, AntGoodsBase antGoods, StoreInfo storeInfo, AddResultListener listener) {
		super(context, R.style.choose_date_dialog_style);
		setContentView(R.layout.add_goods_online_dialog);
		this.setCanceledOnTouchOutside(false);
		this.setCancelable(false);
		mContext = context;
		mAntGoods = antGoods;
		mStoreInfo = storeInfo;
		mAddResultListener = listener;
		mDecimalFormat = new DecimalFormat("#########.##");
		
		mIvImage = (ImageView)findViewById(R.id.add_goods_online_dialog_pic);
		mBtnCancel = (Button)findViewById(R.id.add_goods_online_dialog_bottom_btn_cancel);
		mBtnAdd = (Button)findViewById(R.id.add_goods_online_dialog_bottom_btn_add);
		mTvPromptShelf = (TextView)findViewById(R.id.add_goods_online_dialog_prompt_shelf);
		mTvGoodsTitle = (TextView)findViewById(R.id.add_goods_online_dialog_title);
		mTvGoodsDes = (TextView)findViewById(R.id.add_goods_online_dialog_des);
		mEtPricePurchase = (EditText)findViewById(R.id.add_goods_online_dialog_price_purchase_et);
		mEtPriceSell = (EditText)findViewById(R.id.add_goods_online_dialog_price_sell_et);
		mEtDiscount = (EditText)findViewById(R.id.add_goods_online_dialog_discount_et);
		mEtPriceByDiscount = (EditText)findViewById(R.id.add_goods_online_dialog_price_by_discount_et);
		mEtStore = (EditText)findViewById(R.id.add_goods_online_dialog_store_et);
		
		mBtnCancel.setOnClickListener(this);
		mBtnAdd.setOnClickListener(this);
		mEtPricePurchase.addTextChangedListener(mTextWatcherForPricePurchase);
		mEtPriceSell.addTextChangedListener(mTextWatcherForPriceSell);
		mEtDiscount.addTextChangedListener(mTextWatcherForDiscount);
		mEtStore.addTextChangedListener(mTextWatcherForStore);
		
		if(mAntGoods != null) {
			ImageLoader.getInstance().displayImage(mAntGoods.getImageUrl(), mIvImage, AntHomeApplication.imageDisplayOptions);
			mTvGoodsDes.setText(mAntGoods.getDescription());
			
			mEtPricePurchase.setText("");
			mEtPriceSell.setText("");
			mEtDiscount.setText(mDecimalFormat.format(mOriginDiscount));
			mEtPriceByDiscount.setText("");
			mEtStore.setText("");
		}
	}
	
	@Override
	public void onClick(View v) {
		if(v.equals(mBtnCancel)) {
			// 取消
			this.dismiss();
		}
		else if(v.equals(mBtnAdd)) {
			// 添加
			this.checkAndAdd();
		}
	}
	
	private void checkAndAdd() {
		if(isCommiting) {
			UtilTools.showMyToast(mContext, mContext.getResources().getString(R.string.prompt_is_commiting));
			return;
		}
		
		if(TextUtils.isEmpty(mEtPricePurchase.getText().toString())) {
			// 检查商品进价
			UtilTools.showMyToast(mContext, mContext.getResources().getString(R.string.add_goods_check_prompt_purchase));
			return;
		}
		else if(TextUtils.isEmpty(mEtPriceSell.getText().toString())) {
			// 检查商品售价
			UtilTools.showMyToast(mContext, mContext.getResources().getString(R.string.add_goods_check_prompt_sell));
			return;
		}
		else if(TextUtils.isEmpty(mEtStore.getText().toString())) {
			// 检查商品库存
			UtilTools.showMyToast(mContext, mContext.getResources().getString(R.string.add_goods_check_prompt_store));
			return;
		}
		
		String styleName = mAntGoods.getStyle();
		String kindName = mAntGoods.getKind();
		Log.d("CEXX", "CEXX => save => styleName : " + styleName);
		Log.d("CEXX", "CEXX => save => kindName : " + kindName);
		if(TextUtils.isEmpty(styleName) || TextUtils.isEmpty(kindName)) {
			Toast.makeText(
					mContext,
					R.string.goods_handle_attr_modify_prompt_failed,
					Toast.LENGTH_SHORT).show();
			return;
		}
		
		List<String> storeIdList = new ArrayList<String>();
		if(mStoreInfo != null) {
			storeIdList.add(mStoreInfo.getStoreid());
		}
		isCommiting = true;
		RetrieveDataAsyn.getInstance().getGoodsBySrcId(storeIdList, mAntGoods.getObjectId(), -1, new RetrieveDataListener() {
			@Override
			public void dataRetrieved(int requestId, Object data) {
				GoodsList goodsList = (GoodsList)data;
				Log.d("CEXX", "CEXX => saveStyle => goodsList.getTotalNum : " + goodsList.getTotalNum());
				if(goodsList.getGoodList() == null || goodsList.getGoodList().size() == 0) {
					goodsAdd();
				}
				else {
					isCommiting = false;
					Toast.makeText(
							mContext,
							R.string.add_goods_dialog_prompt_double,
							Toast.LENGTH_SHORT).show();
				}
			}
		});
	}
	
	private void goodsAdd() {
		AlertDialog dialog = new AlertDialog.Builder(mContext)
				.setTitle(R.string.order_ensure_order_commit_prompt)
				.setMessage(R.string.add_goods_dialog_prompt_add)
				.setNegativeButton(R.string.sure,
						new DialogInterface.OnClickListener() {
							@Override
							public void onClick(DialogInterface dialog,
									int which) {
								saveStyle();
							}
						})
				.setPositiveButton(R.string.cancel,
						new DialogInterface.OnClickListener() {
							@Override
							public void onClick(DialogInterface dialog,
									int which) {
								isCommiting = false;
							}
						}).create();
		dialog.setCanceledOnTouchOutside(false);
		dialog.setCancelable(false);
		dialog.show();
	}
	
	private void saveStyle() {
		String styleName = mAntGoods.getStyle();
		Log.d("CEXX", "CEXX => saveStyle => styleName : " + styleName);
		final AntGoodsStyles style = new AntGoodsStyles();
		style.setName(styleName);
		style.setUserId(AVUser.getCurrentUser().getObjectId());
		RetrieveDataAsyn.getInstance().checkAndSaveStyle(style, 0, new RetrieveDataListener() {
			@Override
			public void dataRetrieved(int requestId, Object data) {
				AntGoodsStyles style = (AntGoodsStyles)data;
				Log.d("CEXX", "CEXX => saveStyle => style.getObjectId : " + style.getObjectId());
				saveKind(style);
			}
		});
		
//		style.saveInBackground(new SaveCallback() {
//			@Override
//			public void done(AVException arg0) {
//				if (arg0 == null) {
//					Log.d("CEXX", "CEXX => saveStyle => suc => style.getObjectId : " + style.getObjectId());
//					saveKind(style);
//				} else {
//					Log.d("CEXX", "CEXX => saveStyle => fai => Exception : " + arg0.toString());
//					Toast.makeText(
//							mContext,
//							R.string.goods_handle_attr_modify_prompt_failed,
//							Toast.LENGTH_SHORT).show();
//				}
//				AddGoodsOnLineDialog.this.dismiss();
//			}
//		});
	}
	
	private void saveKind(AntGoodsStyles style) {
		String kindName = mAntGoods.getKind();
		Log.d("CEXX", "CEXX => saveKind => kindName : " + kindName);
		GoodsKind kind = new GoodsKind();
		kind.setName(kindName);
		kind.setUserId(AVUser.getCurrentUser().getObjectId());
		kind.getStyleRelation().add(style);
		RetrieveDataAsyn.getInstance().checkAndSaveKind(kind, style, 0, new RetrieveDataListener() {
			@Override
			public void dataRetrieved(int requestId, Object data) {
				GoodsKind kind = (GoodsKind)data;
				Log.d("CEXX", "CEXX => saveKind => kind.getObjectId : " + kind.getObjectId());
				saveGoods();
			}
		});
		
//		kind.saveInBackground(new SaveCallback() {
//			@Override
//			public void done(AVException arg0) {
//				if (arg0 == null) {
//					Log.d("CEXX", "CEXX => saveKind => suc");
//					saveGoods();
//				} else {
//					Log.d("CEXX", "CEXX => saveKind => fai => Exception : " + arg0.toString());
//					Toast.makeText(
//							mContext,
//							R.string.goods_handle_attr_modify_prompt_failed,
//							Toast.LENGTH_SHORT).show();
//				}
//				AddGoodsOnLineDialog.this.dismiss();
//			}
//		});
	}
	
	private void saveGoods() {
		if(mStoreInfo == null) {
			mHandler.post(new Runnable() {
				@Override
				public void run() {
					Toast.makeText(
							mContext,
							R.string.goods_handle_attr_modify_prompt_failed_no_store,
							Toast.LENGTH_SHORT).show();
				}
			});
			isCommiting = false;
			return;
		}
		
		final AntGoods antGoods = new AntGoods();
		antGoods.setInPrice(mTempPricePurchase);
		antGoods.setPrice(mTempPriceSell);
		antGoods.setDiscount(mTempDiscount);
		antGoods.setStock(mTempStore);
		antGoods.setUserId(mStoreInfo.getStoreid());
		antGoods.setStoreId(mStoreInfo.getStoreid());
		antGoods.setDescription(mAntGoods.getDescription());
		antGoods.setImageFile(mAntGoods.getImageAVFile());
		antGoods.setShowTag(0);
		antGoods.setUnit(mAntGoods.getUnit());
		antGoods.setWeighUnit(mAntGoods.getWeighUnit());
		antGoods.setWeighStep(mAntGoods.getWeighStep());
		antGoods.setWeighAble(mAntGoods.isWeighAble());
		antGoods.setSrcId(mAntGoods.getObjectId());
		antGoods.setKind(mAntGoods.getKind());
		antGoods.setStyle(mAntGoods.getStyle());
		antGoods.setIsFromLib(true);
		antGoods.setTotalSales(0);
		
		antGoods.saveInBackground(new SaveCallback() {
			@Override
			public void done(AVException arg0) {
				isCommiting = false;
				if (arg0 == null) {
					Log.d("CEXX", "CEXX => saveGoods => suc");
					Toast.makeText(
							mContext,
							R.string.goods_handle_attr_modify_prompt_successful,
							Toast.LENGTH_SHORT).show();
					if(mAddResultListener != null) {
						mAddResultListener.addSuccessful(antGoods);
					}
				} else {
					Log.d("CEXX", "CEXX => saveGoods => fai => Exception : " + arg0.toString());
					Toast.makeText(
							mContext,
							R.string.goods_handle_attr_modify_prompt_failed,
							Toast.LENGTH_SHORT).show();
				}
				AddGoodsOnLineDialog.this.dismiss();
			}
		});
	}
}















